package com.bjc.sdx.activity;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.bjc.sdx.R;
import com.bjc.sdx.service.MyService1;

public class ServiceActivity_2 extends Activity {
    private Button butBindStart;
    private Button butBindStop;
    private Intent intent;
    private ServiceConnection serviceConnection;
    private final String TAG = "MyService1";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.service2_layout);
        butBindStart = (Button) findViewById(R.id.but_bindStart);
        butBindStop = (Button) findViewById(R.id.but_bindStop);

        butBindStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(ServiceActivity_2.this, MyService1.class);
                serviceConnection = new ServiceConnection() {

                    /**
                     * 在与服务链接是调用
                     * @param name
                     * @param service
                     */
                    @Override
                    public void onServiceConnected(ComponentName name, IBinder service) {
                        Log.i(TAG, "onServiceConnected: ");
                        MyService1.MyBinder myBinder = (MyService1.MyBinder) service;
                        myBinder.callSend();
                    }

                    /**
                     * 在非正常断开时调用
                     * @param name
                     */
                    @Override
                    public void onServiceDisconnected(ComponentName name) {
                        Log.i(TAG, "onServiceDisconnected: ");
                    }
                };
                //绑定启动
                bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);
            }
        });

        butBindStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(serviceConnection);
            }
        });

    }

}
